package com.itheima.reggie.common;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.internal.OSSUtils;
import com.aliyun.oss.model.Callback;
import com.itheima.reggie.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/common")
@Slf4j
public class OssController {
    @Autowired
    private AliOssUtil aliOssUtil;
    // 填写待上传的本地文件的完整路径。
    private String localFilePath;
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private String endpoint = "oss-cn-nanjing.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private String accessKeyId = "LTAI5tCcXk9Ky3egQYxvt1yW";
    private String accessKeySecret = "cpXQjlRDcVR3MAO94dq1sOk7KvFOiw";
    // 填写Bucket名称。
    private String bucketName = "itheima-reggie-lishaohong";
    // 填写不包含Bucket名称在内的Object的完整路径。
    private String objectName;
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    String ossUploadBackUrl;
    /**
     * 获取网络图片流
     *
     * @param
     * @return
     */
    public InputStream getImageStream() {
        try {
            if(ossUploadBackUrl == null){
                return null;
            }
            HttpURLConnection connection = (HttpURLConnection) new URL(ossUploadBackUrl).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + ossUploadBackUrl);
        }
        return null;
    }
    @GetMapping("/download")
    public void getFileUrl(HttpServletResponse response, String name){
        try {
            if(((name != null) && (!name.equals("undefined")))){
                ossUploadBackUrl = name;
            }

            //输入流，通过输入流读取文件内容

            InputStream fileInputStream = getImageStream();
            if(fileInputStream == null){
                return;
            }
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 表单上传。
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    private R<String> PostObject(HttpServletRequest request, MultipartFile file) throws Exception {

        log.info("文件上传：{}",file);

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径

            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            request.getSession().setAttribute("image" ,ossUploadBackUrl);
            return R.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }

        return R.error("failed");

    }
    private static void setCallBack(Map<String, String> formFields, Callback callback) {
        if (callback != null) {
            String jsonCb = OSSUtils.jsonizeCallback(callback);
            String base64Cb = BinaryUtil.toBase64String(jsonCb.getBytes());
            formFields.put("callback", base64Cb);
            if (callback.hasCallbackVar()) {
                Map<String, String> varMap = callback.getCallbackVar();
                for (Map.Entry<String, String> entry : varMap.entrySet()) {
                    formFields.put(entry.getKey(), entry.getValue());
                }
            }
        }
    }

}

